var util = require('util');
var EventEmitter = require('events').EventEmitter;

// a client record
var tick = 'tick';
var interval = 1000 * 60 * 7;

function ClientItemAuth(deviceUuid, socket) {
	this.deviceUuid = deviceUuid;
	this.socket = socket;
	this.lastTick = new Date().getTime();
	this.nextTimeout = null;
	console.log("new socket,uuid=" + deviceUuid);
}
util.inherits(ClientItemAuth, EventEmitter);

ClientItemAuth.prototype.start = function() {
	console.log("auth socket start listen ... ");
	var that = this;
	that.setNewTimer();

	// socket data handler
	that.socket.on("data", function(chunk) {
		var data = chunk.toString();
		console.log("receive data:" + chunk);
		if (tick !== data) {
			console.log("undefined msg:" + data);
			return;
		}

		// tick msg
		that.getTick();
	});
}

ClientItemAuth.prototype.getTick = function() {
	console.log("getTick");
	var that = this;
	that.lastTick = new Date().getTime();
	that.socket.write("tick");
	that.setNewTimer();
}

ClientItemAuth.prototype.sendMsg = function(msg) {
	console.log("sendMsg:" + msg);
	if (!this.socket.writable) {
		this.emit("socket_invisible");
		return;
	}
	this.socket.write(msg);
}

ClientItemAuth.prototype.setNewTimer = function() {
	console.log("setNewTimer");
	var that = this;
	if (that.nextTimeout) {
		clearTimeout(that.nextTimeout);
	}
	that.nextTimeout = setTimeout(function() {
		that.emit("tick_timeout");
	}, interval);
}

ClientItemAuth.prototype.finish = function() {
	console.log("finish auth socket");
	this.deviceUuid = null;
	this.socket.end();
	this.socket = null;
	this.lastTick = null;
	if (this.nextTimeout) {
		clearTimeout(this.nextTimeout);
		this.nextTimeout = null;
	}
}

module.exports = ClientItemAuth;